//
//  NSUserDefaults+NSIndexPath.m
//  Pods
//
//  Created by Thomas Quan on 2017/5/8.
//
//

#import "NSUserDefaults+NSIndexPath.h"

#define LFTMCSessionId @"LFTMCSessionId"
#define LFTMCDATA      @"LFTMCDATA"

@implementation NSUserDefaults (NSIndexPath)


/* 数组的每一项的数据格式
 *  dict:{
 *     LFTMCSessionId: 'xxxx',  // 记录聊天页的sessionId
 *     LFTMCDATA     : data,    // 记录聊天页的最后位置
 *  }
 */


- (NSIndexPath *)indexPathForKey:(NSString *)key AndSessionId:(NSString *)sessionId {
    NSMutableArray *array = [[self arrayForKey:key] mutableCopy];
    
    for (NSInteger i=0; i<array.count; i++) {
        NSMutableDictionary *dict = (NSMutableDictionary *)[array[i] mutableCopy];
        if (dict[LFTMCSessionId] && [dict[LFTMCSessionId] isEqualToString:sessionId]) {
            NSData *data = [dict objectForKey:LFTMCDATA];
            NSIndexPath *indexPath = (NSIndexPath *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
            return indexPath;
        }
    }
    
    return nil;
}

- (void)setIndexPath:(NSIndexPath *)indexPath WithSessionId:(NSString *)sessionId forKey:(NSString *)key{
    NSMutableArray *array = [[self arrayForKey:key] mutableCopy];
    if (array == nil) {
        array = [[NSMutableArray alloc] init];
    }
    BOOL isFind = NO;
    for (NSInteger i=0; i<array.count; i++) {
        NSMutableDictionary *dict = (NSMutableDictionary *)[array[i] mutableCopy];
        if (dict[LFTMCSessionId] && [dict[LFTMCSessionId] isEqualToString:sessionId]) {
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:indexPath];
            [dict setObject:data forKey:LFTMCDATA];
            [array replaceObjectAtIndex:i withObject:dict];
            isFind = YES;
            break;
        }
    }
    if (!isFind) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:indexPath];
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
        [dict setObject:data forKey:LFTMCDATA];
        [dict setObject:sessionId forKey:LFTMCSessionId];
        [array addObject:dict];
    }
    [self setObject:array forKey:key];
    [self synchronize];
}

@end
